//
//  AVRecordViewController.m
//  BTAVEditor
//
//  Created by TMAC on 2020/2/4.
//  Copyright © 2020 XMac. All rights reserved.
//

#import "AVRecordViewController.h"
#import "BTAVPreviewView.h"
#import <Masonry.h>
#define MAS_SHORTHAND

#define MAS_SHORTHAND_GLOBALS

@interface AVRecordViewController ()<CAAnimationDelegate,AVCaptureFileOutputRecordingDelegate,AVCaptureMetadataOutputObjectsDelegate>

@property (weak, nonatomic) IBOutlet BTAVPreviewView *previewView;

@property (weak, nonatomic) IBOutlet UIImageView *recordImage;

@property (strong, nonatomic) UIView *maskView;


@property (strong, nonatomic) AVCaptureSession *session;
@property (strong, nonatomic) AVCaptureDeviceInput *activeVideoInput;
@property (strong, nonatomic) AVCaptureFileOutput *videoOutput;
@property (strong, nonatomic) dispatch_queue_t videoQueue;

@property (strong, nonatomic) AVCaptureMetadataOutput *metadataOutput;



@end

@implementation AVRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configUI];
    
    [self configData];
    
}


-(void)configData{
    [((AVCaptureVideoPreviewLayer *)self.previewView.layer) setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    [self setupSession];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [UIView animateWithDuration:0.25 animations:^{
            self.maskView.transform = CGAffineTransformMakeScale(0.001, 0.001);
        } completion:^(BOOL finished) {
            [self.maskView removeFromSuperview];
        }];
    });
}

-(void)configUI{
    self.maskView = [UIView new];
    self.maskView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.maskView];
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.bottom.equalTo(@0);
    }];
}


-(void)setupSession{
    self.session = [[AVCaptureSession alloc] init];
    AVCaptureDevice *vedioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    
    AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:vedioDevice error:nil];
    AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil];
    if (videoInput) {
        if ([self.session canAddInput:videoInput]) {
            [self.session addInput:videoInput];
            self.activeVideoInput = videoInput;
        }
    }
    
    if (audioDevice) {
        if ([self.session canAddInput:audioInput]) {
            [self.session addInput:audioInput];
        }
    }
    
    AVCaptureMovieFileOutput *movieOutput = [[AVCaptureMovieFileOutput alloc]init];

    if ([self.session canAddOutput:movieOutput]) {
        [self.session addOutput:movieOutput];
        self.videoOutput = movieOutput;
    }
    //人脸检测
    self.metadataOutput = [AVCaptureMetadataOutput new];
    [self.metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    if ([self.session canAddOutput:self.metadataOutput]) {
        [self.session addOutput:self.metadataOutput];
        self.metadataOutput.metadataObjectTypes = @[AVMetadataObjectTypeFace];
    }
    
    
    self.videoQueue = dispatch_queue_create("video queue", NULL);
    
    [self.previewView setSession:self.session];
    
    [self startSession];
    
    
}

-(void)startSession{
    if (![self.session isRunning]) {
        dispatch_async(self.videoQueue, ^{
            [self.session startRunning];
        });
    }
}

-(void)stopSession{
    if ([self.session isRunning]) {
        dispatch_async(self.videoQueue, ^{
            [self.session stopRunning];
        });
    }
}

-(void)startRecord{
    if (![self.videoOutput isRecording]) {
        [self.videoOutput startRecordingToOutputFileURL:[self exportUrl] recordingDelegate:self];
    }
}

-(NSURL *)exportUrl{
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/test.mp4",filePath]];
}


-(void)stopRecord{
    if ([self.videoOutput isRecording]) {
        [self.videoOutput stopRecording];
    }
}

- (IBAction)recordAction:(UITapGestureRecognizer *)sender {
    if ([self.videoOutput isRecording]) {
        [self stopRecord];
    }else{
        [self startRecord];
    }
}


- (IBAction)switchCameraAction:(UITapGestureRecognizer *)sender {
    
//    CAKeyframeAnimation
//    CABasicAnimation
    CATransition *transition = [CATransition animation];
    transition.duration = 2;
    transition.fillMode = kCAFillModeRemoved;
    transition.type = @"rippleEffect";
    transition.subtype = kCATransitionFromTop;
    transition.delegate = self;
    [self.previewView.layer addAnimation:transition forKey:@"ripple"];
}

//闪光灯只有在拍摄照片的时候 才有用
- (IBAction)flashAction:(UITapGestureRecognizer *)sender {
    AVCaptureDevice *device = self.activeVideoInput.device;
    if ([device isFlashAvailable]) {
        if ([device lockForConfiguration:NULL]) {
            device.flashMode = AVCaptureFlashModeOn;
            [device unlockForConfiguration];
        }
    }
}



-(AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:position];
    return discoverySession.devices.firstObject;
}

/// 返回未激活的摄像头
-(AVCaptureDevice *)inactiveCamera{
    AVCaptureDevice *device = nil;
    if (self.activeVideoInput.device.position == AVCaptureDevicePositionBack) {
        device = [self cameraWithPosition:AVCaptureDevicePositionFront];
    }else{
        device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    }
    return device;
}


///MARK: Animation delegate
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    //转换前、后置摄像头的时候动画结束的时候回调
    AVCaptureDevice *device = [self inactiveCamera];
    AVCaptureDeviceInput *vedioInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:NULL];
    if (vedioInput) {
        [self.session beginConfiguration];
        [self.session removeInput:self.activeVideoInput];
        if ([self.session canAddInput:vedioInput]) {
            [self.session addInput:vedioInput];
            self.activeVideoInput = vedioInput;
        }else{
            [self.session addInput:self.activeVideoInput];
        }
        [self.session commitConfiguration];
    }
}

///MARK: AVCaptureFileOutputRecordingDelegate
-(void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
    NSLog(@"录制完毕");
}

///MARK: AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    NSMutableArray *metaDataFaces = @[].mutableCopy;
    [metadataObjects enumerateObjectsUsingBlock:^(__kindof AVMetadataObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.type isEqualToString:AVMetadataObjectTypeFace]) {
            [metaDataFaces addObject:obj];
        }
    }];
    [self.previewView didDetectFaces:metadataObjects];
}

@end
